package com.cooper.service.admin;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.cooper.dao.admin.AddressDAO;
import com.cooper.entity.AddressEntity;
import com.cooper.util.BeanUtils;
import com.cooper.util.StringUtils;
import com.cooper.vo.AddressVo;
import com.google.common.base.Splitter;
import com.google.common.collect.Lists;

@Service
public class AddressService {
	
	protected Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Autowired
	private LocationService locationService;
	
	@Autowired
	private AddressDAO addressDao;
	
	public Long saveEntity(AddressEntity entity) throws Exception{
		return this.addressDao.saveEntity(entity);
	}
	
	public AddressEntity loadById(long addressId) throws Exception{
		return this.addressDao.loadById(addressId);
	}
	
	public AddressVo getAddressVoByOriginAndOuterId(String origin, long outerId) throws Exception{
		List<AddressVo> retList = this.findByOriginAndOuterId(origin, outerId);
		if(CollectionUtils.isEmpty(retList)){
			return null;
		}
		return retList.get(0);
	}
	
	public List<AddressVo> findByOriginAndOuterId(String origin, long outerId) throws Exception{
		List<AddressVo> ret = new ArrayList<AddressVo>();
		List<AddressEntity> addressList = addressDao.findByOriginAndOuterId(origin, outerId);
		if(addressList!=null){
			StringBuffer strLocationIds = new  StringBuffer();
			StringBuffer strLocationNames = new  StringBuffer();
			for(AddressEntity entity:addressList){
				AddressVo vo = new AddressVo();
				BeanUtils.copyProperties(entity, vo);
				vo.setAddressId(entity.getId());
				Long countryId = entity.getCountryId();
				if(StringUtils.isLongValid(countryId)){
					vo.setCountryName(this.locationService.loadById(countryId).getZhCn());
				}
				strLocationIds.append(StringUtils.isLongValid(entity.getCityId())?","+entity.getCityId():"");
				strLocationIds.append(StringUtils.isLongValid(entity.getStateId())?","+entity.getStateId():"");
				strLocationIds.append(StringUtils.isLongValid(entity.getCountryId())?","+entity.getCountryId():"");
				strLocationIds.append(StringUtils.isLongValid(entity.getContinentId())?","+entity.getContinentId():"");
				if(strLocationIds.toString().startsWith(",")){
					vo.setStrLocationIds(strLocationIds.toString().substring(strLocationIds.toString().indexOf(",")+1));
				}
				vo.setStrLocationIds(strLocationIds.toString());
				strLocationNames.append(StringUtils.isEmpty(entity.getCityName())?"":", "+entity.getCityName());
				strLocationNames.append(StringUtils.isEmpty(entity.getStateName())?"":", "+entity.getStateName());
				strLocationNames.append(StringUtils.isEmpty(entity.getCountryName())?"":", "+entity.getCountryName());
				strLocationNames.append(StringUtils.isEmpty(entity.getContinentName())?"":", "+entity.getContinentName());
				if(strLocationNames.toString().startsWith(",")){
					vo.setStrLocationNames(strLocationNames.toString().substring(strLocationNames.toString().indexOf(",")+1));
				}
				ret.add(vo);
			}
		}
		return ret;
	}
	
	
	/**
	 * 保存地址信息，返回新插入记录的ID
	 * @param addressVo 地址信息
	 * @return
	 * @throws Exception
	 */
	public long saveAddress(AddressVo addressVo) throws Exception{
		AddressEntity entity = null;
		if(StringUtils.isEmpty(addressVo.getStrLocationIds()) || StringUtils.isEmpty(addressVo.getStrLocationNames())){
			return 0;
		}
		List<String> originIdStrList = Splitter.on(",").splitToList(addressVo.getStrLocationIds());
		List<String> originNameList = Splitter.on(",").splitToList(addressVo.getStrLocationNames());
		if(2 > originIdStrList.size() || 2 > originNameList.size()){
			return 0;
		}
		
		boolean bUpdate = false;
		
		Long addressId = addressVo.getAddressId()==null?-1L:addressVo.getAddressId();
		if(addressId==-1){
			AddressVo address = this.getAddressVoByOriginAndOuterId(addressVo.getOrigin(), addressVo.getOuterId());
			if(null != address){
				addressId = address.getAddressId();
			}
		}
		entity = addressDao.loadById(addressId);
		if(null != entity){
			bUpdate = true;
		} else {
			entity = new AddressEntity();
			entity.setOuterId(addressVo.getOuterId());
			entity.setOrigin(addressVo.getOrigin());
		}
		List<Long> originIds = Lists.newArrayList();
		for(String strOriginId: originIdStrList){
			if(StringUtils.isNotBlank(strOriginId)){
				originIds.add(new Long(strOriginId.trim()));
			}
		}
		
		List<String> originNames = Lists.newArrayList();
		for(String str:originNameList){
			if(StringUtils.isNotBlank(str)){
				originNames.add(str.trim());
			}
		}
		Collections.reverse(originIds);
		Collections.reverse(originNames);
		
		entity.setContinentId(originIds.get(0));
		entity.setContinentName(originNames.get(0));
		entity.setCountryId(originIds.get(1));
		entity.setCountryName(originNames.get(1));
		if(originIds.size() > 2 && originNames.size() > 2){
			entity.setStateId(originIds.get(2));
			entity.setStateName(originNames.get(2));
		}
		if(originIds.size() > 3 && originNames.size() > 3){
			entity.setCityId(originIds.get(3));
			entity.setCityName(originNames.get(3));
		}
		entity.setStreet(addressVo.getStreet());
		
		if(bUpdate){
			this.addressDao.updateEntity(entity);
			return entity.getId();
		} else {
			return this.saveEntity(entity);
		}
	}

}
